package com.example.Arithmetic.Lettcode;

import com.example.Arithmetic.Arithmetic.TreeNode;

/**
 * 日期：2023/10/17
 * 时间：11:01
 * 描述：二叉树插入值
 */
public class E04Lettcode701 {
    //    迭代
    public TreeNode insertIntoBST(TreeNode root, int val) {
        if (root == null) {
            return new TreeNode(val);
        }
        TreeNode<Integer> treeNode = root;
        TreeNode<Integer> parent = treeNode;
        while (treeNode != null) {
            parent = treeNode;
            if (treeNode.val > val) {
                treeNode = treeNode.left;
            } else if (treeNode.val < val) {
                treeNode = treeNode.right;
            }
        }
        if (parent.val > val) {
            parent.left = new TreeNode(val);
        } else {
            parent.right = new TreeNode(val);
        }
        return root;
    }

    //递归
    public TreeNode insertIntoBST1(TreeNode<Integer> root, int val) {
        if (root == null) {
            return new TreeNode(val);
        }
        if (root.val > val) {
            root.left = insertIntoBST1(root.left, val);
        } else {
            root.right = insertIntoBST1(root.right, val);
        }
        return root;
    }
}

